from flask import Blueprint, request, Response

from models import User
from exts import db

bp = Blueprint("get_img", __name__, url_prefix="/get_img")

# 获取图片的函数
def do_get_img(img_path):
    with open(img_path, "rb") as f:
        image = f.read()
    return image

# 用户头像
@bp.route("/head_img/<username>", methods=["POST", "GET"])
def head_img(username):
    user = User.query.filter(User.username == username).first()
    if user is None:
        return "no username"
    else:
        img_path = user.headImgPath
        if img_path is None:
            return "no head img"
        try:
            image = do_get_img(img_path=img_path)
            return Response(image, mimetype="image/jpeg")
        except:
            # 存入图片，却找不到，可能是系统出了问题
            return "可能是网络导致图片丢失，请重新上传", 500

# 接收用户头像
@bp.route("/upload_head_img", methods=["POST", "GET"])
def upload_head_img():
    upload_file = request.files["HeadImgFile"]
    # 获取到图片提交的参数,用户邮箱
    user_name = request.form["username"]
    user = User.query.filter(User.username == user_name).first()
    if user is None:
        return "no username"
    else:
        file_name = upload_file.filename
        file_path = "./public/head_img/" +user_name+ "." + file_name.split(".")[-1]
        print(file_path)
        upload_file.save(file_path)
        user.headImgPath = file_path
        db.session.commit()
        # print(upload_file)
        return "upload img success"